import React, {Fragment} from "react";
import {Button, Checkbox, Icon, Tooltip /** , Input, Radio */} from "antd";
import {connect} from "dva";
// import Zcon from "@cbd/icon";
import {openNotificationWithIcon} from "utils/comm";
import {baseTimeoutSetting} from "components/g6edit/structureData";
import NoticeUserAdd from "components/NoticeUserAdd/NoticeUserAdd";
import _get from 'lodash/get';
import BaseDuedateSetting from "./BaseDuedateSetting";
// import UserSelectorModal from "./UserSelectorModal";
// import MessageEditModal from "./MessageEditModal";
import DelayInput from "./DelayInput";
import dsStyles from "./DuedateSetting.less";
import styles from "./Pannel.less";

export const alertCodePattern = /^[a-zA-Z_][a-zA-Z_0-9-]*$/;

// const RadioGroup = Radio.Group;

const datetimeConfig = [
  {label: "天", key: "day"},
  {label: "时", key: "hour", max: 23},
  {label: "分", key: "minute", max: 59},
];

// const PARAMSTYPE = {
//   PROCESS_WARNING: "PROCESS_WARNING", // 流程预警通知
//   PROCESS_TIMEOUT: "PROCESS_TIMEOUT", // 流程超时通知
//   TASK_TIMEOUT: "TASK_TIMEOUT", // 任务超时通知
//   TASK_WARNING: "TASK_WARNING", // 任务预警通知
// };

@connect(({FlowChart, notice_msg: noticeModel}) => ({
  noticeTypeData: FlowChart.noticeTypeData,
  noticeThemeTypeList: noticeModel.noticeThemeTypeList,
}))
class DuedateSetting extends BaseDuedateSetting {
  constructor(props) {
    super(props);
    this.state = {
      alertCodes: [],

      // 用来渲染用户选择弹窗的属性
      users: [],
      channels: [],
      userSelectorVisible: false,
      // record: [],
      noticeType: '', // 超时/预警
    };
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
  }

  componentDidMount() {
    this.getNoticeThemeList();
  }

  getNoticeThemeList = () => {
    const {dispatch} = this.props;
    dispatch({type: 'notice_msg/getNoticeThemeType'});
  }

  componentDidUpdate(prevProps) {
    const {codeRefModel} = this.props;
    if (prevProps.codeRefModel !== codeRefModel) {
      this.setState({alertCodes: []}); // eslint-disable-line
    }
  }

  // initData = (type) => {
  //   const { dispatch } = this.props;
  //   dispatch({
  //     type: "FlowChart/getTemplateListByType",
  //     payload: { type },
  //   }).then(({ errCode, errortext, datas }) => {
  //     if (errCode === 0) {
  //       this.setState({ record: datas[0] });
  //     } else {
  //       this.openNotificationWithIcon(
  //         "warning",
  //         "",
  //         errortext || "获取模板信息失败",
  //       );
  //     }
  //   });
  // };

  onSelectTimeout = (timeoutSetting) => {
    // const { codeRefModel } = this.props;
    // const { type } = codeRefModel;
    // let paramType = "";
    // // 如果当前是 node 节点，模板参数为 任务超时，否则为 流程超时
    // if (type && type === "node") {
    //   paramType = PARAMSTYPE.TASK_TIMEOUT;
    // } else {
    //   paramType = PARAMSTYPE.PROCESS_TIMEOUT;
    // }
    // const { title = "", content = "" } = timeoutSetting;
    // const s = { title, content };
    this.edittingUserType = "timeoutSetting";
    // this.initData(paramType);
    this.setState({
      // ...s,
      userSelectorVisible: true, // eslint-disable-line
      users: _get(timeoutSetting, 'timeoutNotifier.notifier', []).filter((user) => user.type !== 'INIT'),
      noticeType: '超时',
      // paramType,
    });
  };

  onSelectAlert = (alert, idx) => {
    // const { codeRefModel } = this.props;
    // const { type } = codeRefModel;
    // let paramType = "";
    // // 如果当前是 node 节点，模板参数为 任务预警，否则为 流程预警
    // if (type && type === "node") {
    //   paramType = PARAMSTYPE.TASK_WARNING;
    // } else {
    //   paramType = PARAMSTYPE.PROCESS_WARNING;
    // }
    // const { title = "", content = "" } = alert;
    // const s = { title, content };
    this.edittingUserType = "warningSetting";
    this.edittingIndex = idx;
    // this.initData(paramType);
    this.setState({
      // ...s,
      userSelectorVisible: true, // eslint-disable-line
      users: _get(alert, 'warningNotifier.notifier', []).filter((user) => user.type !== 'INIT'),
      noticeType: '预警',
      // paramType
    });
  };

  render() {
    const {
      /** alertCodes, channels, */
      // title = "",
      // content = "",
      userSelectorVisible,
      // record,
      users,
      // paramType,
      noticeType,
    } = this.state;
    const {
      // appId,
      disable,
      // dispatch,
      // modelVariables,
      // codeRefModel,
      type,
      noticeThemeTypeList,
    } = this.props;
    let {timeoutSetting} = this.props;
    timeoutSetting = timeoutSetting || baseTimeoutSetting;
    const {warningSetting = {}} = timeoutSetting;
    const {warningRegular: alerts = []} = warningSetting;
    const showDuedate = timeoutSetting.isTimeout === "true";
    const showWarning = warningSetting.isWarning === "true";

    return (
      <>
        {/* <div className={styles.content_item} style={{ display: "block" }}>
          <span className={styles.item_label} style={{ paddingBottom: 0 }}>
            <Checkbox
              checked={showReCommentdate}
              disabled={disable}
              onChange={(e) => this.onReCommentChecked(e, alerts)}
            >
              节点处理是否必须表达意见
            </Checkbox>
          </span>
        </div> */}
        <div className={styles.content_item} style={{display: "block"}}>
          <span className={styles.item_label} style={{paddingBottom: 0}}>
            <Checkbox
              checked={showDuedate}
              disabled={disable}
              onChange={(e) => this.onTimeoutChecked(e, alerts)}
            >
              超时设置
            </Checkbox>
            <Tooltip placement="topLeft" title="该节点需要多少天完成，只作为一个配置使用">
              <Icon
                style={{cursor: "pointer"}}
                theme="filled"
                type="question-circle"
              />
            </Tooltip>
          </span>
          {showDuedate && (
            <div className={dsStyles.box}>
              {/* <RadioGroup
                style={{ width: "100%", margin: "15px 0 6px" }}
                disabled={disable}
                value={timeoutSetting.calendarType}
                onChange={this.onTimeRadioChange}
              >
                <Radio value="CALENDAR_DAY">日历日</Radio>
                <Radio value="WORKING_DAY">工作日</Radio>
              </RadioGroup> */}
              <div className={styles.delay_box}>
                {datetimeConfig.map(({label, key, ...rest}) => (
                  <DelayInput
                    key={key}
                    label={label}
                    value={timeoutSetting[key]}
                    disabled={disable}
                    name={key}
                    onBlur={this.onTimeoutValueChange}
                    {...rest}
                  />
                ))}
              </div>
              <Button
                className={dsStyles.btn}
                type="primary"
                onClick={() => this.onSelectTimeout(timeoutSetting)}
              >
                通知设置
              </Button>
            </div>
          )}
        </div>
        <div className={styles.content_item} style={{display: "block"}}>
          <span
            className={styles.item_label}
            style={{paddingBottom: 0, marginBottom: 12}}
          >
            <Checkbox
              checked={showWarning}
              disabled={disable || !showDuedate}
              onChange={(e) => this.onWarningCheck(e, alerts)}
            >
              预警设置
            </Checkbox>
            {/* {showWarning ? (
              <RadioGroup
                style={{ width: "100%", margin: "15px 0 6px" }}
                disabled={disable}
                value={warningSetting.calendarType}
                onChange={(e) => this.onWarningRadioChange(e, warningSetting)}
              >
                <Radio value="CALENDAR_DAY">日历日</Radio>
                <Radio value="WORKING_DAY">工作日</Radio>
              </RadioGroup>
            ) : null} */}
            {alerts.map((alert, idx) => (
              <Fragment key={alert.uuid}>
                <div className={dsStyles.box}>
                  {/* <div className={dsStyles.code}>
                    <span className={dsStyles.label}>预警编码：</span>
                    <span className={dsStyles.input}>
                      <Input
                        placeholder="请输入"
                        maxLength={15}
                        onBlur={(e) => {
                          let { value } = e.target;
                          value = (value || "").trim();
                          if (!alertCodePattern.test(value)) {
                            this.openNotificationWithIcon(
                              "warning",
                              "",
                              `预警编码输入格式不正确（支持字母、数字、下划线、中划线，且以字母或者下划线开头）`,
                            );
                          }
                          this.onAlertCodeChange(
                            value,
                            idx,
                            alert,
                            warningSetting,
                            alerts,
                          );
                        }}
                        onChange={(e) => {
                          const { value } = e.target;
                          const { alertCodes: oldCodes } = this.state;
                          oldCodes[idx] = value;
                          const newCodes = [...oldCodes];
                          this.setState({ alertCodes: newCodes });
                        }}
                        style={{ width: 126 }}
                        value={alertCodes[idx] || alert.warningCode}
                      />
                    </span>
                  </div> */}
                  <div className={styles.delay_box}>
                    {datetimeConfig.map(({label, key, ...rest}) => (
                      <DelayInput
                        key={key}
                        label={label}
                        value={alert[key]}
                        disabled={disable}
                        name={key}
                        onBlur={(valueObj) => {
                          this.onAlertValueChange(
                            valueObj,
                            alert,
                            idx,
                            warningSetting,
                            alerts,
                          );
                        }}
                        {...rest}
                      />
                    ))}
                  </div>
                  <div className={dsStyles.btnRow}>
                    {Number(idx) === 0 && (
                      <Button
                        className={dsStyles.iconBtn}
                        type="primary"
                        icon="plus"
                        disabled={Boolean(alerts.length >= 3)}
                        onClick={() => {
                          this.onAddAlert(idx, alerts, warningSetting);
                        }}
                        title="添加预警规则"
                      />
                    )}

                    {alerts.length > 1 && Number(idx) !== 0 ? (
                      <Button
                        className={dsStyles.iconBtn}
                        type="primary"
                        icon="minus"
                        onClick={() => {
                          this.onRemoveAlert(idx, alerts, warningSetting);
                        }}
                        title="删除此预警规则"
                      />
                    ) : null}
                    <Button
                      className={dsStyles.btn}
                      type="primary"
                      onClick={() => {
                        this.onSelectAlert(alert, idx);
                      }}
                    >
                      通知设置
                    </Button>
                  </div>
                </div>
              </Fragment>
            ))}
          </span>
        </div>
        {/* 对应BaseDuedateSetting::onUserSelect版本1
        <UserSelectorModal
          appId={appId}
          candidateUsers={users}
          disable={disable}
          noticeChannel={channels}
          dispatch={dispatch}
          modelVariables={modelVariables}
          onCancel={() => this.setState({ userSelectorVisible: false })}
          onOk={(...args) => this.onUserSelect(alerts, warningSetting, ...args)}
          title="设置通知人"
          visible={userSelectorVisible}
        /> */}
        {/* 对应BaseDuedateSetting::onUserSelect版本2
        userSelectorVisible && (
          <MessageEditModal
            appId={appId}
            disable={disable}
            dispatch={dispatch}
            modelVariables={modelVariables}
            onCancel={() => this.setState({ userSelectorVisible: false })}
            onOk={(...args) =>
              this.onUserSelect(alerts, warningSetting, ...args)
            }
            visible={userSelectorVisible}
            title={title}
            content={content}
            record={record}
            paramType={paramType}
          />
        )}
        */}
        {// 对应BaseDuedateSetting::onUserSelect版本3
          userSelectorVisible && (
            <NoticeUserAdd
              type={type}
              noticeType={noticeType}
              handleCancel={() => this.setState({userSelectorVisible: false})}
              onOk={(...args) =>
                this.onUserSelect(alerts, warningSetting, ...args)
              }
              visible={userSelectorVisible}
              onfirmLoading={false}
              users={users}
              noticeThemeTypeList={noticeThemeTypeList}
            />
          )}
      </>
    );
  }
}

export default DuedateSetting;
